package com.mb.app.appused.data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * 
 * @author xhwwzd
 * 
 * @param <T>
 */

public class DBManager<T> {

	// manager.add(data); //添加数据
	// manager.update(data, add); //更新数据
	// manager.remove(data, CondistionType.AND); //移除数据
	// manager.query(); //查询所有数据
	// manager.findAll(add, CondistionType.AND); //条件数据
	// manager.getSize(); //数据库总行数
	// manager.find(data, CondistionType.AND);//查询单条数据

	// MyData list = (MyData) manager.find(add, CondistionType.AND);
	// if (list != null) {
	// Log.e("info", list.name);
	// }

	public enum CondistionType {
		AND, OR
	};

	public enum ORDER {
		DESC, ASC
	};

	public enum CompareType {
		EQ, LESS, GREATER, NEQ, LIKE
	}

	public ORDER order = ORDER.DESC;

	Class<T> myClass;
	DBHelper helper;
	Context context;
	int VERSION = 1;
	String DABASENAME = "Temp";
	DBManager<T> Instance;

	/**
	 * 创建数据库表格 使用类名作为数据库名
	 * 
	 * @param context
	 * @param myClass
	 */
	public DBManager(Context context, Class<T> myClass) {
		this.myClass = myClass;
		this.context = context;
		DABASENAME = getDBName();
		this.Instance = this;
		creat();
	}

	/**
	 * 创建数据库表格 数据库名称 表格模型
	 * 
	 * @param context
	 * @param dataBase
	 * @param myClass
	 */
	public DBManager(Context context, String dbName, Class<T> myClass) {
		this.myClass = myClass;
		this.context = context;
		DABASENAME = dbName;
		this.Instance = this;
		creat();
	}

	/**
	 * 创建数据表 上下文 数据库信息 表格模型
	 * 
	 * @param context
	 * @param db
	 * @param myClass
	 */
	public DBManager(Context context, DBInfomation db, Class<T> myClass) {
		this.myClass = myClass;
		this.context = context;
		DABASENAME = db.DBName;
		VERSION = db.DBVersion;
		this.Instance = this;
		creat();
	}

	/**
	 * 创建表格
	 * 
	 * @return
	 */
	boolean creat() {
		if (myClass == null)
			return false;
		helper = new DBHelper(this.context, DABASENAME + ".sqlite", null, VERSION) {
			@Override
			String getCreatSQL() {
				// TODO Auto-generated method stub
				// return Instance.getCreatSQL();
				return null;
			}

			@Override
			String getonUpgradeSQL() {
				// TODO Auto-generated method stub
				return null;
			}
		};
		creatTable();
		return false;
	}

	/**
	 * 创建表格
	 * 
	 * @return
	 */
	void creatTable() {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = getCreatSQL();
		db.execSQL(sql);
		db.close();
	}

	/**
	 * 创建表格
	 * 
	 * @param t
	 * @return
	 */
	String getCreatSQL() {
		String sql = "";
		sql = "create table if not exists {tableName}( id integer primary key autoincrement,";
		sql = sql.replace("{tableName}", myClass.getSimpleName());

		for (Field temp : myClass.getFields()) {
			if (temp.getName().compareTo("id") == 0)
				continue;
			sql += temp.getName() + " " + getType(temp) + ",";
		}
		sql += ")";
		sql = sql.replace(",)", ")");
		return sql;
	}

	/**
	 * 获取数据类型
	 * 
	 * @param temp
	 * @return
	 */
	String getType(Field temp) {
		String type = "";
		if (temp.getType().getSimpleName().compareTo("int") == 0) {
			type = "interger";
		}
		if (temp.getType().getSimpleName().compareTo("String") == 0) {
			type = "text";
		}
		if (temp.getType().getSimpleName().compareTo("boolean") == 0) {
			type = "interger";
		}

		if (temp.getType().getSimpleName().compareTo("Integer") == 0) {
			type = "interger";
		}
		if (temp.getType().getSimpleName().compareTo("char") == 0) {
			type = "varchar(256)";
		}
		return type;
	}

	/**
	 * 获取数据库名称
	 * 
	 * @param t
	 * @return
	 */
	String getDBName() {
		return myClass.getSimpleName();
	}

	/**
	 * 获取表格名称
	 * 
	 * @param t
	 */
	public String getTableName() {
		return myClass.getSimpleName();
	}

	/**
	 * 添加数据
	 * 
	 * @param t
	 */
	public void add(T t) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "insert into {tableName} {file} values {temp}";
		sql = sql.replace("{tableName}", getTableName());
		String f = "(";
		String p = "(";
		List<Object> objs = new ArrayList<Object>();
		for (Field temp : t.getClass().getFields()) {
			try {
				if (getActive(temp.get(t))) {
					f += "" + temp.getName() + ",";
					p += "?,";
				}
			} catch (IllegalAccessException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IllegalArgumentException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				objs.add(temp.get(t));
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		f += ")";
		p += ")";
		f = f.replace(",)", ")");
		p = p.replace(",)", ")");
		sql = sql.replace("{file}", f);
		sql = sql.replace("{temp}", p);

		Object[] ts = new Object[objs.size()];
		for (int i = 0; i < ts.length; i++) {
			ts[i] = objs.get(i);
		}
		db.execSQL(sql, ts);
		db.close();
	}

	/**
	 * 删除数据
	 * 
	 * @param t
	 */
	@SuppressWarnings("unchecked")
	public void remove(T t, CondistionType type) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "delete from {table} ";
		sql = sql.replace("{table}", getTableName());
		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;
		case OR:
			sql += getCondistionOr(t);
			break;
		}
		db.execSQL(sql);
		db.close();
	}

	/**
	 * 删除数据
	 * 
	 * @param t
	 */
	public void remove(T[] t, CondistionType type) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "delete from {table} ";
		sql = sql.replace("{table}", getTableName());
		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;
		case OR:
			sql += getCondistionOr(t);
			break;
		}
		db.execSQL(sql);
		db.close();
	}

	/**
	 * 更新数据
	 * 
	 * @param t
	 */
	@SuppressWarnings("unchecked")
	public void update(T condistion, T data) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "update {table} set ";
		sql = sql.replace("{table}", getTableName());
		for (Field temp : data.getClass().getFields()) {
			try {
				if (getActive(temp.get(data))) {
					sql += temp.getName() + " ='" + temp.get(data).toString() + "' , ";
				}
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		sql = sql.substring(0, sql.length() - 3);
		sql += " " + getCondistionAnd(condistion);
		db.execSQL(sql);
		db.close();
	}

	/**
	 * 更新数据
	 * 
	 * @param condistion
	 * @param data
	 */
	public void update(T[] condistion, T data) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "update {table} set ";
		sql = sql.replace("{table}", getTableName());
		for (Field temp : data.getClass().getFields()) {
			try {
				if (getActive(temp.get(data))) {
					sql += temp.getName() + " ='" + temp.get(data).toString() + "' , ";
				}
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		sql = sql.substring(0, sql.length() - 3);
		sql += " " + getCondistionAnd(condistion);
		db.execSQL(sql);
		db.close();
	}

	/**
	 * 清空数据库
	 */
	public void clean() {

	}

	/**
	 * 查询数据
	 * 
	 * @param t
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> findAll(T t, CondistionType type) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select DISTINCT * from {table} ";
		sql = sql.replace("{table}", getTableName());
		List<T> Result = new ArrayList<T>();

		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;

		case OR:
			sql += getCondistionOr(t);
			break;
		}
		sql += getOrder();
		Cursor cursor = db.rawQuery(sql, null);

		// if (cursor.moveToFirst()) {
		// for (int i = 0; i < cursor.getCount(); i++) {
		// JSONObject obj = new JSONObject();
		// for (int sp = 1; sp < cursor.getColumnCount(); sp++) {
		// try {
		// obj.put(cursor.getColumnName(sp), cursor.getString(sp));
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// Result.add(creatBean(obj));
		// }
		// }

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	/**
	 * 条件查询
	 * 
	 * @param t
	 * @param type
	 * @return
	 */
	public List<T> findAll(T[] t, CondistionType type) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select DISTINCT * from {table} ";
		sql = sql.replace("{table}", getTableName());
		List<T> Result = new ArrayList<T>();

		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;

		case OR:
			sql += getCondistionOr(t);
			break;
		}
		sql += getOrder();
		Cursor cursor = db.rawQuery(sql, null);

		// if (cursor.moveToFirst()) {
		// for (int i = 0; i < cursor.getCount(); i++) {
		// JSONObject obj = new JSONObject();
		// for (int sp = 1; sp < cursor.getColumnCount(); sp++) {
		// try {
		// obj.put(cursor.getColumnName(sp), cursor.getString(sp));
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// Result.add(creatBean(obj));
		// }
		// }

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	@SuppressWarnings("unchecked")
	public List<T> selectAll(T t, CondistionType type) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select DISTINCT * from {table} ";
		sql = sql.replace("{table}", getTableName());
		List<T> Result = new ArrayList<T>();
		sql += " " + getSeletWehre(t);
		sql = sql.replace("{code}", "=");
		switch (type) {
		case AND:
			sql = sql.replace("{pcode}", " and ");
			break;
		case OR:
			sql = sql.replace("{pcode}", " or ");
			break;
		}

		Log.e("info", "" + sql);

		Cursor cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	public List<T> selectAll(T[] t, CondistionType type) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select DISTINCT * from {table} ";
		sql = sql.replace("{table}", getTableName());
		List<T> Result = new ArrayList<T>();
		sql += " " + getSeletWehre(t);
		sql = sql.replace("{code}", "=");
		switch (type) {
		case AND:
			sql = sql.replace("{pcode}", " and ");
			break;
		case OR:
			sql = sql.replace("{pcode}", " or ");
			break;
		}

		Log.e("info", "" + sql);

		Cursor cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	/**
	 * 查询固定个数
	 * 
	 * @param t
	 * @param type
	 * @param size
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> findSize(T t, CondistionType type, int size, int page) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select * from {table} ";
		sql = sql.replace("{table}", getTableName());
		List<T> Result = new ArrayList<T>();

		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;

		case OR:
			sql += getCondistionOr(t);
			break;
		}
		sql += getOrder();
		sql += getLimit(size, size * page);
		Cursor cursor = db.rawQuery(sql, null);

		// if (cursor.moveToFirst()) {
		// for (int i = 0; i < cursor.getCount(); i++) {
		// JSONObject obj = new JSONObject();
		// for (int sp = 1; sp < cursor.getColumnCount(); sp++) {
		// try {
		// obj.put(cursor.getColumnName(sp), cursor.getString(sp));
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// Result.add(creatBean(obj));
		// }
		// }

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	/**
	 * 查询指定长度
	 * 
	 * @param t
	 * @param type
	 * @param size
	 * @param page
	 * @return
	 */
	public List<T> findSize(T[] t, CondistionType type, int size, int page) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select * from {table} ";
		sql = sql.replace("{table}", getTableName());
		List<T> Result = new ArrayList<T>();

		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;

		case OR:
			sql += getCondistionOr(t);
			break;
		}
		sql += getOrder();
		sql += getLimit(size, size * page);
		Cursor cursor = db.rawQuery(sql, null);

		// if (cursor.moveToFirst()) {
		// for (int i = 0; i < cursor.getCount(); i++) {
		// JSONObject obj = new JSONObject();
		// for (int sp = 1; sp < cursor.getColumnCount(); sp++) {
		// try {
		// obj.put(cursor.getColumnName(sp), cursor.getString(sp));
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// Result.add(creatBean(obj));
		// }
		// }

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	/**
	 * 查询单条数据
	 * 
	 * @param t
	 * @return
	 */
	public T find(T t, CondistionType type) {
		List<T> temp = new ArrayList<T>();
		temp = findAll(t, type);
		if (temp.size() < 1)
			return null;
		return temp.get(0);
	}

	/**
	 * 查询
	 * 
	 * @param t
	 * @param type
	 * @return
	 */
	public T find(T[] t, CondistionType type) {
		List<T> temp = new ArrayList<T>();
		temp = findAll(t, type);
		if (temp.size() < 1)
			return null;
		return temp.get(0);
	}

	/**
	 * 模糊查询
	 * 
	 * @param t
	 * @param type
	 */

	@SuppressWarnings("unchecked")
	public List<T> findLike(T t, CondistionType type) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select * from {table}";
		sql = sql.replace("{table}", getTableName());
		switch (type) {
		case AND:
			sql += getLikeCondistionAnd(t);
			break;
		case OR:
			sql += getLikeCondistionOr(t);
			break;
		}
		sql += getOrder();
		Log.e("info", sql);
		Cursor cursor = db.rawQuery(sql, null);
		List<T> Result = new ArrayList<T>();
		cursor.moveToFirst();

		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	/**
	 * 模糊查询
	 * 
	 * @param t
	 * @param type
	 * @return
	 */
	public List<T> findLike(T[] t, CondistionType type) {

		List<T> Result = new ArrayList<T>();
		for (T temp : t) {
			List<T> read = findLike(temp, type);
			for (T readChild : read) {
				Result.add(readChild);
			}
		}
		return Result;
	}

	/**
	 * 直接运行SQL语句
	 * 
	 * @param sql
	 * @return
	 */
	public List<T> runSql(String sql) {
		List<T> Result = new ArrayList<T>();
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	/**
	 * 根据条件查询
	 * 
	 * @param columns
	 * @param args
	 * @param compare
	 * @param type
	 * @return
	 */
	public List<T> runQuery(String[] columns, String[] args, CompareType compare, CondistionType type) {
		String sql = "select * from {table} where ";
		sql = sql.replace("{table}", getTableName());

		int min = columns.length < args.length ? columns.length : args.length;
		for (int i = 0; i < min; i++) {
			ColumnSet set = new ColumnSet(columns[i], args[i], compare);
			if (set.getEmpty())
				continue;
			sql += set.getSting();
			if (i == min - 1)
				break;
			switch (type) {
			case AND:
				sql += " and ";
				break;
			case OR:
				sql += " or ";
				break;
			}
		}
		sql += getOrder();
		List<T> Result = new ArrayList<T>();
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		return Result;
	}

	/**
	 * 更具条件查询
	 * 
	 * @param set
	 * @param type
	 * @return
	 */
	public List<T> runQuery(ColumnSet[] set, CondistionType type) {
		String sql = "select * from {table} where ";
		sql = sql.replace("{table}", getTableName());
		for (int i = 0; i < set.length; i++) {
			if (set[i].getEmpty())
				continue;

			sql += set[i].getSting();
			if (i == set.length - 1)
				break;
			switch (type) {
			case AND:
				sql += " and ";
				break;
			case OR:
				sql += " or ";
				break;
			}
		}
		sql += getOrder();
		List<T> Result = new ArrayList<T>();
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}

		return Result;
	}

	/**
	 * 根据条件查询
	 * 
	 * @param set
	 * @return
	 */
	public List<T> runQuery(ColumnSet[] set) {
		String sql = "select * from {table} where ";
		sql = sql.replace("{table}", getTableName());
		for (int i = 0; i < set.length; i++) {
			if (set[i].getEmpty())
				continue;
			if (i < set.length - 1) {
				sql += set[i].getStringCondistion();
			} else {
				sql += set[i].getSting();
			}
		}
		sql += getOrder();
		Log.e("info", sql);
		List<T> Result = new ArrayList<T>();
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}

		return Result;
	}
	
	/**
	 * 根据条件查询
	 * 
	 * @param set
	 * @return
	 */
	public List<T> runQuery(CondistionType type,ColumnSet[]... set) {
		String sql = "select * from {table} where ";
		sql = sql.replace("{table}", getTableName());
		for (int i = 0; i < set.length; i++) {
//			if (set[i].getEmpty())
//				continue;
//			if (i < set.length - 1) {
//				sql += set[i].getStringCondistion();
//			} else {
//				sql += set[i].getSting();
//			}
			sql+=" (";
			for(int t=0;t<set[i].length; t++){
				if( set[i][t] ==null || set[i][t].getEmpty())continue;
				if (t == set[i].length - 1) {
					Log.e("info", "get string");
					sql += set[i][t].getSting();
				}else {
					Log.e("info", "get condistion string");
					sql += set[i][t].getStringCondistion();
				}
			}
			
			sql+=" ) {pcode}";
		}
		sql=sql.substring(0, sql.length()-7);
		
		switch (type) {
		case AND:
			sql = sql.replace("{pcode}", " and ");
			break;
		case OR:
			sql = sql.replace("{pcode}", " or ");
			break;
		}

		
		sql += getOrder();
		Log.e("info", sql);
		
		List<T> Result = new ArrayList<T>();
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			Log.e("info", ">>>>>>>>>>>>");
			for (int sp = 0; sp < cursor.getColumnCount(); sp++) {
				try {
					obj.put(cursor.getColumnName(sp), cursor.getString(sp));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}

		return Result;
	}

	/**
	 * 嵌套查询
	 * 
	 * @param child
	 * @param find
	 */
	public void findChild(T[] child, T find) {
		String sql = "select * from {table} where ";
		sql = sql.replace("{table}", getTableName());

	}

	/**
	 * 去重复
	 * 
	 * @param list
	 * @return
	 */
	public List<T> removerepeat(List<T> list) {

		return null;
	}

	/**
	 * 判断俩数据是否相等
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public boolean isEq(T a, T b) {
		if (a.equals(b)) {
			return true;
		}
		return false;
	}

	/**
	 * 获取表格记录数量
	 * 
	 * @return
	 */
	public long getSize() {
		int count = 0;
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select count(*) from {table}";
		sql = sql.replace("{table}", getTableName());
		Cursor cursor = db.rawQuery(sql, null);
		if (cursor.moveToFirst()) {
			count = cursor.getInt(0);
		}
		db.close();
		return count;
	}

	@SuppressWarnings("unchecked")
	public long getSize(T t, CondistionType type) {
		int count = 0;
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select count(*) from {table}";
		sql = sql.replace("{table}", getTableName());

		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;

		case OR:
			sql += getCondistionOr(t);
			break;
		}

		Cursor cursor = db.rawQuery(sql, null);
		if (cursor.moveToFirst()) {
			count = cursor.getInt(0);
		}
		db.close();
		return count;
	}

	/**
	 * 获取长度
	 * 
	 * @param t
	 * @param type
	 * @return
	 */
	public long getSize(T[] t, CondistionType type) {
		int count = 0;
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "select count(*) from {table}";
		sql = sql.replace("{table}", getTableName());

		switch (type) {
		case AND:
			sql += getCondistionAnd(t);
			break;

		case OR:
			sql += getCondistionOr(t);
			break;
		}

		Cursor cursor = db.rawQuery(sql, null);
		if (cursor.moveToFirst()) {
			count = cursor.getInt(0);
		}
		db.close();
		return count;
	}

	/**
	 * 查询所有数据
	 * 
	 * @return
	 */
	public List<T> query() {
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.query(getTableName(), null, null, null, null, null, " id " + getOrder(order)); //

		List<T> Result = new ArrayList<T>();

		// if (cursor.moveToFirst()) {
		// for (int i = 0; i < cursor.getCount(); i++) {
		// JSONObject obj = new JSONObject();
		// cursor.move(i);
		// for (int t = 0; t < cursor.getColumnCount(); t++) {
		// try {
		//
		// Log.e("info", i + ">>>" + cursor.getColumnName(t)
		// + ">>>>" + cursor.getString(t));
		// obj.put(cursor.getColumnName(t), cursor.getString(t));
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// Result.add(creatBean(obj));
		// }
		// }
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			JSONObject obj = new JSONObject();
			for (int t = 0; t < cursor.getColumnCount(); t++) {
				try {
					obj.put(cursor.getColumnName(t), cursor.getString(t));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cursor.moveToNext();
			Result.add(creatBean(obj));
		}
		db.close();
		return Result;
	}

	/**
	 * 生成数据
	 * 
	 * @return
	 */
	T creatBean(JSONObject obj) {
		Gson gson = new Gson();
		T item = (T) gson.fromJson(obj.toString(), myClass);
		return item;
	}

	/**
	 * 布尔转数值
	 * 
	 * @param obj
	 * @return
	 */
	String getCondition(Object obj) {
		String a = obj.toString();
		if (obj == null || obj.toString().compareTo("false") == 0)
			a = "0";
		if (obj != null && obj.toString().compareTo("true") == 0)
			a = "1";
		if (obj != null && obj.toString().length() < 1)
			a = "NULL";
		return a;
	}

	/**
	 * 是否为条件
	 * 
	 * @param obj
	 * @return
	 */
	boolean getActive(Object obj) {

		if (obj == null)
			return false;
		// Log.e("info", obj.toString());
		if (obj instanceof Integer) {
			int value = ((Integer) obj).intValue();
			if (value < 0)
				return false;
		} else if (obj instanceof String) {
			String s = (String) obj;

		} else if (obj instanceof Double) {
			double d = ((Double) obj).doubleValue();

		} else if (obj instanceof Float) {
			float f = ((Float) obj).floatValue();

		} else if (obj instanceof Long) {
			long l = ((Long) obj).longValue();

		} else if (obj instanceof Boolean) {
			boolean b = ((Boolean) obj).booleanValue();

		} else if (obj instanceof Date) {
			Date d = (Date) obj;
		}
		
		if (obj != null && obj.toString().length() < 1)
			return false;
		if (obj != null && obj.toString().length() > 0)
			return true;
		return false;
	}

	/**
	 * 获取条件
	 * 
	 * @param t
	 * @return
	 */
	String getCondistionAnd(T... t) {
		String where = " where ";
		String sql = "";
		for (int i = 0; i < t.length; i++) {

			for (Field temp : t[i].getClass().getFields()) {
				try {
					if (getActive(temp.get(t[i]))) {
						sql += temp.getName() + "='" + getCondition(temp.get(t[i])) + "' and ";
					}
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		if (sql.length() > 5) {
			where += sql.substring(0, sql.length() - 5);
		} else {
			where += "* ";
		}
		return where;
	}

	String getLikeCondistionAnd(T... t) {
		String where = " where ";
		String sql = "";
		for (int i = 0; i < t.length; i++) {

			for (Field temp : t[i].getClass().getFields()) {
				try {
					if (getActive(temp.get(t[i]))) {
						sql += temp.getName() + " like '%" + getCondition(temp.get(t[i])) + "%' and ";
					}
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		if (sql.length() > 5) {
			where += sql.substring(0, sql.length() - 5);
		} else {
			where += "* ";
		}
		return where;
	}

	/**
	 * 获取条件
	 * 
	 * @param t
	 * @return
	 */
	String getCondistionOr(T... t) {
		String where = " where ";
		String sql = "";
		for (int i = 0; i < t.length; i++) {
			for (Field temp : t[i].getClass().getFields()) {
				try {
					if (getActive(temp.get(t[i]))) {
						sql += temp.getName() + "='" + getCondition(temp.get(t[i])) + "' or ";
					}
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		if (sql.length() > 5) {
			where += sql.substring(0, sql.length() - 4);
		} else {
			where += "* ";
		}
		return where;
	}

	String getLikeCondistionOr(T... t) {
		String where = " where ";
		String sql = "";
		for (int i = 0; i < t.length; i++) {
			for (Field temp : t[i].getClass().getFields()) {
				try {
					if (getActive(temp.get(t[i]))) {
						sql += temp.getName() + " like '%" + getCondition(temp.get(t[i])) + "%' or ";
					}
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		if (sql.length() > 5) {
			where += sql.substring(0, sql.length() - 4);
		} else {
			where += "* ";
		}
		return where;
	}

	public String getSeletWehre(T... t) {
		String where = " where ";
		String sql = "";
		for (int i = 0; i < t.length; i++) {
			sql += " (";
			for (Field temp : t[i].getClass().getFields()) {
				try {
					if (getActive(temp.get(t[i]))) {
						sql += " " + temp.getName() + " {code} '" + getCondition(temp.get(t[i]) + "' and ");
					}
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			sql = sql.substring(0, sql.length() - 4);
			sql += " ) {pcode}";
		}

		if (sql.length() > 5) {
			where += sql.substring(0, sql.length() - 8);
		} else {
			where += "* ";
		}
		return where;
	}

	/**
	 * 获取排序条件
	 * 
	 * @param order
	 * @return
	 */
	String getOrder() {
		return getOrder("id");
	}

	/**
	 * 获取排序
	 * 
	 * @param order
	 * @return
	 */
	String getOrder(ORDER order) {
		String t = "desc";
		switch (order) {
		case ASC:
			t = "asc";
			break;

		case DESC:
			t = "desc";
			break;
		}
		return t;
	}

	/**
	 * 排序
	 * 
	 * @param lable
	 * @return
	 */
	String getOrder(String lable) {
		String sql = " order by {lable} {order}";
		sql = sql.replace("{lable}", lable);
		switch (order) {
		case DESC:
			sql = sql.replace("{order}", "desc");
			break;
		case ASC:
			sql = sql.replace("{order}", "asc");
			break;
		}
		return sql;
	}

	/**
	 * 分页查询
	 * 
	 * @param count
	 * @param start
	 * @return
	 */
	String getLimit(int count, int start) {
		String sql = " limit {count} Offset {start}";
		sql = sql.replace("{count}", count + "");
		sql = sql.replace("{start}", start + "");
		return sql;
	}

	/**
	 * 数据库信息
	 * 
	 * @author xhwwzd
	 *
	 */
	public class DBInfomation {
		public String DBName = "";
		public int DBVersion = 1;
	}

	/**
	 * 条件查询
	 * 
	 * @author xhwwzd
	 *
	 */
	public static class ColumnSet {
		public String columnName;
		public String columnValue;
		public CompareType compareType = CompareType.EQ;
		public CondistionType conditionType = CondistionType.AND;

		public ColumnSet() {

		}

		public ColumnSet(String name, String value) {
			this.columnName = name;
			this.columnValue = value;
		}

		public ColumnSet(String name, String value, CompareType type) {
			this.columnName = name;
			this.columnValue = value;
			this.compareType = type;
		}

		public ColumnSet(String name, String value, CompareType type, CondistionType condistion) {
			this.columnName = name;
			this.columnValue = value;
			this.compareType = type;
			this.conditionType = condistion;
		}

		public boolean getEmpty() {
			boolean a = columnValue == null || columnValue.length() < 1;
			a = (a | columnName == null || columnName.length() < 1);
			return a;
		}

		public String getSting() {
			String sp = " " + columnName;
			switch (compareType) {
			case EQ:
				sp += " = '" + columnValue + "' ";
				break;
			case GREATER:
				sp += " > '" + columnValue + "' ";
				break;
			case LESS:
				sp += " < '" + columnValue + "' ";
				break;
			case NEQ:
				sp += " != '" + columnValue + "' ";
				break;
			case LIKE:
				sp += " like '%" + columnValue + "%' ";
				break;
			}

			switch (conditionType) {
			case AND:

				break;
			case OR:

				break;
			}
			return sp;
		}

		public String getStringCondistion() {

			String sp = " " + columnName;

			switch (compareType) {
			case EQ:
				sp += " = '" + columnValue + "' ";
				break;
			case GREATER:
				sp += " > '" + columnValue + "' ";
				break;
			case LESS:
				sp += " < '" + columnValue + "' ";
				break;
			case NEQ:
				sp += " != '" + columnValue + "' ";
				break;
			case LIKE:
				sp += " like '%" + columnValue + "%' ";
				break;
			}

			switch (conditionType) {
			case AND:
				sp += " and ";
				break;
			case OR:
				sp += " or  ";
				break;
			}
			return sp;
		}
	}

}
